package com.otaku.crawler.parser;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.otaku.crawler.model.USAShopCNPojo;
import com.otaku.crawler.util.Constants;

public class USAShopCNParser {
	private static final String URL_HEADER = "http://www.usashopcn.com/";
	
	public static List<USAShopCNPojo> parse(String xml){
		try {
			List<USAShopCNPojo> rl = new ArrayList<USAShopCNPojo>();
			
			Document d = DocumentHelper.parseText(xml);
			d.setXMLEncoding("UTF-8");
			
			return parse(d);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	private static List<USAShopCNPojo> parse(Document d){
		List<USAShopCNPojo> rl = new ArrayList<USAShopCNPojo>();
		USAShopCNPojo po = new USAShopCNPojo();
		
		Element e = d.getRootElement();
		Iterator i = e.elementIterator();
		
		while(i.hasNext()){
			Element e1 = (Element) i.next();
			String av = e1.attributeValue("class");
			if(av.equals("img")){
				Element e3 = (Element) ((Element) e1.elementIterator().next()).elementIterator().next();
				String imgUrl = e3.attributeValue("src");
				
				po.setImgUrl(imgUrl.replaceAll(Constants.AND_REPLACE, "&"));
			}else if(av.equals("name")){
				Element e2 = (Element) e1.elementIterator().next();
				String url = URL_HEADER+e2.attributeValue("href");
				
				po.setUrl(url.replaceAll(Constants.AND_REPLACE, "&"));
				po.setName(e2.getText().replaceAll(Constants.AND_REPLACE, "&"));
			}else if(av.equals("market_price")){
				po.setMarketPrice(e1.getText().trim().replaceAll(Constants.AND_REPLACE, "&"));
			}else if(av.equals("proxy_price")){
				po.setProxyPrice(e1.getText().trim().replaceAll(Constants.AND_REPLACE, "&"));
				
				rl.add(po);
				po=new USAShopCNPojo();
			}
		}
		
		return rl;
	}
}
